<template>
  <div class="select-container">
    <el-select clearable placeholder="请选择省份" v-model="province">
      <el-option
        v-for="item in allAreaData"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      clearable
      :disabled="!province"
      placeholder="请选择城市"
      v-model="city"
    >
      <el-option
        v-for="item in cityOptions"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      clearable
      :disabled="!province || !city"
      placeholder="请选择区域"
      v-model="area"
    >
      <el-option
        v-for="item in areaOptions"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import All_AREA_DATA from "../lib/pca-code.json";
let allAreaData = ref(All_AREA_DATA);
const emits = defineEmits(["change"]);

let province = ref<string>("");
let city = ref<string>("");
let area = ref<string>("");

interface AreaData {
  code: string;
  name: string;
  children?: AreaData[];
}

let cityOptions = ref<AreaData[]>([]);
watch(
  () => province.value,
  (val) => {
    let cityData = allAreaData.value.find((item) => item.code === val);
    if (cityData) {
      cityOptions.value = cityData.children || [];
    }
    city.value = "";
    area.value = "";
  }
);
let areaOptions = ref<AreaData[]>([]);
watch(
  () => city.value,
  (val) => {
    let areaData = cityOptions.value.find((item) => item.code === val);
    if (areaData) {
      areaOptions.value = areaData.children || [];
    }
    area.value = "";
  }
);

//最后一项选中后 向父组件派发数据
watch(
  () => area.value,
  (val) => {
    if (val) {
      let areaData = areaOptions.value.find((item) => item.code === val);
      let cityData = cityOptions.value.find((item) => item.code === city.value);
      let provinceData = allAreaData.value.find(
        (item) => item.code === province.value
      );
      if (areaData && cityData && provinceData) {
        emits("change", {
          info: {
            province: {
              name: provinceData.name,
              code: province.value,
            },
            city: {
              name: cityData.name,
              code: city.value,
            },
            area: {
              name: areaData.name,
              code: area.value,
            },
          },
          code: [province.value, city.value, area.value],
        });
      }
    }
  }
);
</script>

<style lang="scss" scoped>
.select-container {
  .el-select {
    margin-right: 10px;
    width: 150px;
  }
}
</style>
